from django.http import JsonResponse
from django.views import View

from articleType.models import ArticleType, SysArticleTypeSerializer


class OperateArticeTypeView(View):

    def post(self, request):
        id = request.POST.get("id", None)
        type_name = request.POST.get("type_name")
        is_active = request.POST.get("is_active")
        if id is None or id == "-1" or id == "":  # 当id为空值时，新增类型
            try:
                articleType = ArticleType.objects.create(
                    type_name=type_name,
                    is_active=1
                )
                # 查询所有类型
                types = ArticleType.objects
                return JsonResponse(
                    {"code": 200, "info": "添加成功！", "types": SysArticleTypeSerializer(types, many=True).data})
            except Exception as a:
                return JsonResponse({"code": 500, "info": "添加失败！"})
        else:  # 当id不为空值时，修改类型
            try:
                articleType = ArticleType.objects.get(id=id)
                articleType.id = id
                articleType.type_name = type_name
                articleType.is_active = is_active
                articleType.save()
                # 查询所有公告数据
                types = ArticleType.objects
                return JsonResponse(
                    {"code": 200, "info": "修改成功！", "types": SysArticleTypeSerializer(types, many=True).data})
            except Exception as a:
                return JsonResponse({"code": 500, "info": "修改失败！"})


class SelectArticeTypeView(View):  # 查询类型
    def post(self, request):
        is_active = request.POST.get("is_active", None)
        try:
            if is_active in [None, "", "-1"]:
                types = ArticleType.objects.all()
            else:
                types = ArticleType.objects.filter(is_active=is_active)
            return JsonResponse(
                {"code": 200, "info": "查询成功！", "types": SysArticleTypeSerializer(types, many=True).data})

        except Exception as e:
            return JsonResponse({"code": 500, "info": "查询失败！", "error": e})
